%%
%% This is a fork of clientovich
%%
%% The original implementation could not handle several
%% connections from a single node. (Because of registration)
%%
%% This implementation returns the main loop pid, this must
%% be included in query calls.
%%
-module(clientovich2).
-compile(export_all).

-define(TCP_OPTIONS, [list, {packet,    0},
                            {active,    false},
                            {reuseaddr, true}]).

start(Address,Port) ->
    Pid = spawn(?MODULE,loop,[0]),
    Pid ! {start, Address, Port},
    Pid.
    
start() ->
    start("localhost",25000).

put(Pid,Key,Value) ->
    Pid ! {put,Key,Value,self()},
    receive
        {reply,Reply} -> Reply
    end.

get(Pid,Key) ->
    Pid ! {get,Key,self()},
    receive
        {reply,Reply} -> Reply
    end.

del(Pid,Key) ->
    Pid ! {del,Key,self()},
    receive
        {reply,Reply} -> Reply
    end.
    
stop(Pid) ->
    Pid ! {die}.
    
loop(Socket) ->
    receive
        {start, Address, Port} ->
            case gen_tcp:connect(Address,Port,?TCP_OPTIONS) of
                {ok,NewSocket} -> 
                    loop(NewSocket);
                {error,Reason} ->
                    io:fwrite("Client: Failed connecting to socket; " ++ Reason)
            end;

        {del,Key,Pid} ->
            clientiface:make_and_send(Socket,"DEL",Key),
            Reply = clientiface:get_message(Socket),
            Pid ! {reply, Reply},
            loop(Socket);
        {get,Key,Pid} ->
            clientiface:make_and_send(Socket,"GET",Key),
            Reply = clientiface:get_message(Socket),
            Pid ! {reply, Reply},
            loop(Socket);
        {put,Key,Value,Pid} ->
            clientiface:make_and_send(Socket,"PUT",Key,Value),
            Reply = clientiface:get_message(Socket),
            Pid ! {reply, Reply},
            loop(Socket);
        {die} ->
            gen_tcp:close(Socket),
            ok;
        _   ->
            io:format("clientovich: Unknown message!"),
            loop(Socket)
    end.

